package cn.bigfire.wedesk.net.fivesocket.codec;



import cn.bigfire.wedesk.net.fivesocket.frame.AbsFiveFrame;
import cn.bigfire.wedesk.net.fivesocket.frame.BinaryFiveFrame;
import cn.bigfire.wedesk.net.fivesocket.frame.CloseFiveFrame;
import cn.bigfire.wedesk.net.fivesocket.frame.ContinueFiveFrame;
import cn.bigfire.wedesk.net.fivesocket.frame.OpCodes;
import cn.bigfire.wedesk.net.fivesocket.frame.PingFiveFrame;
import cn.bigfire.wedesk.net.fivesocket.frame.PongFiveFrame;
import cn.bigfire.wedesk.net.fivesocket.frame.TextFiveFrame;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;

import java.util.List;

/**
 * 废物Socket
 * FiveSocket 一个根据websocket简化得到的
 * 由于数据报文头只占5个字节 所以叫 "废物Socket"
 */
public class FiveSocketEncoder extends MessageToMessageEncoder<AbsFiveFrame> {

    @Override
    protected void encode(ChannelHandlerContext ctx, AbsFiveFrame msg, List<Object> out) throws Exception {
        try {
            byte opCode = OpCodes.PONG_CODE;//没有匹配到的类型就回Pong
            if (msg instanceof ContinueFiveFrame) {
                opCode = OpCodes.CONTINUE_CODE;
            } else if (msg instanceof TextFiveFrame) {
                opCode = OpCodes.TEXT_CODE;
            } else if (msg instanceof BinaryFiveFrame) {
                opCode = OpCodes.BINARY_CODE;
            } else if (msg instanceof CloseFiveFrame) {
                opCode = OpCodes.CLOSE_CODE;
            } else if (msg instanceof PingFiveFrame) {
                opCode = OpCodes.PING_CODE;
            } else if (msg instanceof PongFiveFrame) {
                opCode = OpCodes.PONG_CODE;
            } else {
                System.err.println();
            }
            //添加应用层协议头
            ByteBuf outBuf = Unpooled.buffer();
            outBuf.writeByte(opCode);

            int len = msg.content().readableBytes();

            //弹性len字段(可压缩空间，但编解码繁琐)
//            if (len <= 125) {
//                outBuf.writeByte((byte) len);
//            } else if (len < Short.MAX_VALUE) {
//                outBuf.writeByte(126);//标记为Short
//                outBuf.writeShort((short) len);
//            } else if (len < Integer.MAX_VALUE) {
//                outBuf.writeByte(127);//标记为Int
//                outBuf.writeInt(len);
//            }
            //固定int4字节len字段(固定4字节,但编解码简单)
            outBuf.writeInt(len);

            outBuf.writeBytes(msg.content());
            out.add(outBuf);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
